package com.factory.iamp.controller;

import com.factory.iamp.pojo.Line;
import com.factory.iamp.pojo.LineWithInfo;
import com.factory.iamp.pojo.User;
import com.factory.iamp.service.LineService;
import com.factory.iamp.utils.helper.PageHelper;
import com.factory.iamp.utils.token.LinePermissionToken;
import com.factory.iamp.utils.token.LoginToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/line")
@Validated
public class LineController {
    @Resource
    private LineService lineService;

    @GetMapping("/all")
    @LoginToken
    public List<LineWithInfo> getAllLine(@RequestAttribute("iampUser") User user) {
        return lineService.getAllLine(user.getUid());
    }

    @GetMapping("/member/list/{lid}/{limit}/{page}")
    public PageHelper getAllMemberInLine(
            @PathVariable("limit") int limit,
            @PathVariable("page") int page,
            @PathVariable("lid") int lid
    ) {

        PageHelper result = new PageHelper(lineService.getMemberCountInLine(lid), page, limit);
        result.setData(lineService.getMemberInLine(lid, result.calOffset(), result.getLimit()));
        return result;
    }

    @PostMapping("/to/{lid}")
    @LoginToken
    public void changeLine(@PathVariable("lid") int lid, @RequestAttribute("iampUser") User user) {
        lineService.changeLine(lid, user);
    }

    @PostMapping("/member/add")
    @LoginToken
    @LinePermissionToken(verifyType = "a")
    public void addMember(@RequestBody Map<String, String> data, @RequestAttribute("iampUser") User user) {
        lineService.addMember(user.getLine(), data.get("uid"), data.get("r"), data.get("w"), "0");
    }

    @PostMapping("/member/add/admin/{lid}")
    @LoginToken(checkPrivate = true)
    public void addMemberAdmin(@PathVariable("lid") int lid, @RequestBody Map<String, String> data) {
        lineService.addMember(lid, data.get("uid"), data.get("r"), data.get("w"), data.get("a"));
    }

    @PostMapping("/add")
    @LoginToken(checkPrivate = true)
    public void addLine(@RequestBody Map<String, String> data, @RequestAttribute("iampUser") User user) {
        lineService.addLine(data.get("name"), user.getUid());
    }

    @PostMapping("/set/{lid}")
    @LoginToken(checkPrivate = true)
    public void setLine(@PathVariable("lid") int lid, @RequestBody Map<String, String> data) {
        lineService.setLine(lid, data);
    }

    @PostMapping("/permission/set/{lid}")
    @LoginToken
//    @LinePermissionToken(verifyType = "a")
    public void setLinePermission(@PathVariable("lid") int lid, @RequestBody Map<String, String> data) {
        lineService.setLinePermission(lid, data);
    }

    @DeleteMapping("/delete/{lid}")
    @LoginToken(checkPrivate = true)
    public void deleteLine(@PathVariable("lid") int lid) {
        lineService.deleteLine(lid);
    }
}
